package com.timmy.chi.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.timmy.chi.R;
import com.timmy.chi.ui.fragment.HomeFragment;
import com.timmy.chi.ui.fragment.MoreFragment;
import com.timmy.chi.ui.fragment.OrderFragment;
import com.timmy.chi.ui.fragment.UserFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private LinearLayout mLayout;
    private List<Fragment> mFragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initFragment();
        initBottom();
        changUI(0);
    }

    private void initView() {
        mLayout = (LinearLayout) findViewById(R.id.main_bottome_switcher_container);
    }


    /**
     * 初始化fragment
     */
    private void initFragment() {
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new OrderFragment());
        mFragmentList.add(new UserFragment());
        mFragmentList.add(new MoreFragment());
    }

    /**
     * 初始化状态栏
     */
    private void initBottom() {
        //选中谁就禁用谁
        int count = mLayout.getChildCount();

        //找出 layout 的布局
        for (int i = 0; i < count; i++) {
            final View childAt = mLayout.getChildAt(i);
            childAt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = mLayout.indexOfChild(childAt);
                    changUI(index);
                }
            });
        }
    }

    /**
     * 切换到 index 个页面
     */
    private void changUI(int index) {
        // 第 index 个禁用,其他的启用
        int count = mLayout.getChildCount();

        for (int i = 0; i < count; i++) {
            View child = mLayout.getChildAt(i);
            if (i == index) {
                // 禁用
                setEnabled(child, false);
            } else {
                //启用
                setEnabled(child, true);
            }
        }

        //切换Fragment
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_fragment_container, mFragmentList.get(index))
                .commit();
    }

    public void setEnabled(View child, boolean enabled) {
        child.setEnabled(enabled);

        if (child instanceof ViewGroup) {
            ViewGroup childX = (ViewGroup) child;
            int count = childX.getChildCount();
            for (int i = 0; i < count; i++) {
                View item = childX.getChildAt(i);
                setEnabled(item, enabled);
            }
        }

    }
}
